<template>
  <div class="maintenance-calendar full-height bg-white page-content content">
    <yz-condition-filter
          v-model="queryParams"
          @resetSearch="resetSearch"
          @onSubmit="onSubmit"
          class="padding-t-20"
        >
        <select-tooltip
            v-model="queryParams.workshopId"
            :multiple="false"
            :options="workshopslist"
            msg="所在车间"
          ></select-tooltip>
        <select-tooltip
            v-model="queryParams.deviceType"
            :multiple="false"
            isShowAll
            :options="deviceTypesList"
            msg="设备类型"
          ></select-tooltip>
        <yz-input
              v-model.trim="queryParams.stockinDate"
              class="q-mr-md"
              :isRange="false"
              inputType="date"
              dateType="week"
              dateFormat= "YYYY-第w周"
              title="保养日期"
         ></yz-input>
        </yz-condition-filter>
        <div class="flex margin-r-20 justify-end q-mb-md">
          <div class="flex margin-l-20" v-for="(item,index) in maintenanceStatusOptions" :key="index">
            <div class="circle" :style="{ background:item.color }"></div>
            <div>{{item.label}}</div>
          </div>
        </div>
      <q-table
          :data="tableData"
          :columns="columns"
          separator="cell"
          style="margin-bottom: 20px"
          class="myTable scroll"
          :loading="isTableLoading"
          :pagination.sync="pagination"
          :hide-bottom="tableData.length > 0"
          no-data-label="暂无数据"
          color="primary"
        >
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td v-for="(item, index) in props.cols" :key="item.name" style="height:100px; padding:0">
            <div v-if="index === 0" class="text-center">
              <div>
                {{props.row['deviceName']}}({{props.row['deviceCode']}})
              </div>
              <div>
                {{props.row['model']}}({{props.row['deviceTypeName']}})
              </div>
            </div>
            <!-- 显示颜色区域 -->
            <div v-else class="full-height">
                <div  v-for="(v,i) in props.row[item.name]"
                      :key="i"
                      :style="{ background:getColor(v.orderStatus, true),height: getHeight(props.row[item.name]), borderBottom: `2px solid${getColor(v.orderStatus)}`}"
                      class="flex justify-center items-center relative-position cursor-pointer">
                    <div class="calendar-title" :style="{ color:getColor(v.orderStatus)}">{{v.number}}</div>
                        <q-popup-proxy>
                            <q-card style="border-radius: 0px">
                              <q-list>
                                <q-item clickable v-for="(item, index) in v.data" :key="index" @click="onDetail(v, item)" class=" cursor-pointer" :class="{'border-bottom': index !== v.data.length-1}">
                                  <q-item-section class="flex">
                                    <div class="flex">
                                      <div style="margin-right: 40px">
                                        <div style="color: #5F77FD">
                                          保养单号: {{item.orderNo}}
                                        </div>
                                        <div>
                                          保养项目: {{item.itemName}}
                                          <q-icon
                                            v-if="item.isShowAbnormal === '2'"
                                            name="iconfont icontubiao-113"
                                            color="red"
                                            class="abnormal q-ml-sm"/>
                                        </div>
                                      </div>
                                      <div>
                                        <div>班制名称: {{item.shiftName || '--'}}</div>
                                        <div>保养人: {{item.operatorNameList && item.operatorNameList.join() || '--'}}</div>
                                      </div>
                                    </div>
                                  </q-item-section>
                                </q-item>
                                <q-separator />
                              </q-list>
                                <q-inner-loading :showing="isShowDetaiLoading" style="z-index: 99">
                                    <q-spinner-gears size="50px" color="primary" />
                                </q-inner-loading>
                            </q-card>
                        </q-popup-proxy>
                    <q-icon v-if="getShowAbnormal(v.data)"
                            name="iconfont icontubiao-113"
                            color="red"
                            class="abnormal cursor-pointer">
                    </q-icon>
                </div>
            </div>
          </q-td>
        </q-tr>
      </template>
      <template v-slot:no-data>
          <div class="full-width row flex-center font-size-14" style="color: #999">
            暂无数据
          </div>
      </template>
    </q-table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import _ from 'lodash'
import moment from 'moment'
import { getCalendarList } from 'src/boot/maintenance/maintenance-plan'
export default {
  name: 'maintenance-calendar',
  components: {
  },
  data () {
    return {
      queryParams: {
        workshopId: '',
        deviceType: 'all',
        startDate: '',
        endDate: '',
        stockinDate: new Date()
      },
      isTableLoading: false,
      isShowDetaiLoading: false,
      tableData: [],
      columnClone: [],
      pagination: {
        rowsPerPage: 0
      }
    }
  },
  computed: {
    ...mapGetters({
      'workshopslist': 'maintenance/workshopslist',
      'deviceTypesList': 'maintenance/deviceTypesList'
    }),
    //  保养状态枚举
    maintenanceStatusOptions () {
      return this.$getEnum(this.Enums.MAINTENANCE_STATUS)
    },
    columns () {
      return [
        { name: 'deviceName', label: '设备', align: 'left', field: 'deviceName' },
        ...this.columnClone
      ]
    }
  },
  mounted () {
    this.initData()
  },
  methods: {
    initData () {
      this.columnClone = this.getWeek(this.queryParams.stockinDate)
      this.queryParams.workshopId = _.get(this.workshopslist[0], 'value', '')
      this.getList()
    },
    resetSearch () {
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      this.queryParams.workshopId = _.get(this.workshopslist[0], 'value', '')
    },
    onSubmit () {
      this.columnClone = this.getWeek(this.queryParams.stockinDate)
      this.getList()
    },
    // 点击详情
    onDetail (val, item) {
      const params = {
        maintenanceStatus: val.orderStatus,
        orderNo: item.orderNo,
        startDate: val.date,
        endDate: val.date
      }
      this.$router.push({
        name: 'maintenanceOrder',
        params
      })
    },
    // 跳转到保养工单
    goMaintenanceOrder (val) {
      // this.$router.push({
      //   path: '/main/repair/maintenance-order',
      //   query: {}
      // })
    },
    // 获取背景色
    getColor (value, isBgColor) {
      return value ? isBgColor ? this.$getEnum(this.Enums.MAINTENANCE_STATUS, value).bgColor : this.$getEnum(this.Enums.MAINTENANCE_STATUS, value).color : ''
    },
    // 获取div 高度
    getHeight (rows) {
      return !_.isEmpty(rows) ? `${100 / rows.length}%` : '0'
    },
    getShowAbnormal (data) {
      return data.some(v => v.isShowAbnormal === '2')
    },
    getList () {
      if (!this.queryParams.workshopId) {
        this.$message.warning('请选择车间')
        return
      }
      this.tableData = []
      this.isTableLoading = true
      const params = {
        ...this.queryParams
      }
      getCalendarList(params).then((result) => {
        this.tableData = this.getTableData(result.data)
        this.isTableLoading = false
      }).catch((err) => {
        this.isTableLoading = false
        console.log(err)
      })
    },
    // 拼接数据
    getTableData (data) {
      const member = data.reduce((arr, item) => {
        item.list && item.list.map(v => {
          item[v.date] = v.data.filter(i => !_.isEmpty(i.data)).map(y => {
            const k = y
            k.date = v.date
            return k
          })
        })
        arr.push(item)
        return arr
      }, [])
      return member
    },
    // 获取周表头数据
    getWeek (val) {
      let startDay = moment(val).startOf('isoWeek')
      let endDay = moment(val).endOf('isoWeek')
      let diff = endDay.diff(startDay, 'days')
      let member = []
      for (let i = 0; i <= diff; i++) {
        const firstDay = moment(val).startOf('isoWeek')
        let everyDay = firstDay.add(i, 'd')
        let weekday = everyDay.weekday()
        member.push({
          label: `${this.CommonConfig.date_locale.days[weekday]}(${everyDay.format('MM-DD')})`,
          name: everyDay.format('YYYY-MM-DD'),
          field: everyDay.format('YYYY-MM-DD'),
          align: 'left'
        })
      }
      this.queryParams.startDate = startDay.format('YYYY-MM-DD')
      this.queryParams.endDate = endDay.format('YYYY-MM-DD')
      return member
    }
  }
}
</script>
<style scoped lang="scss">
  .border-bottom{
    border-bottom: 1px solid #d3d3d3;
  }
  .maintenance-calendar{
    .circle {
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin: auto 5px;
    }
    .calendar-title{
      font-size: 9px;
      font-family: PingFang SC;
      font-weight: bold;
    }
    .border-b{
      height: 2px;
    }
    .abnormal{
      position: absolute;
      top: 6px;
      right: 6px;
    }
  }
</style>
